package com.qk.management.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.qk.entity.domain.business.BusinessCountDO;
import com.qk.entity.domain.clue.ClueCountDO;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.entity.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.qk.common.constant.CacheConstants.CACHE_PORTAL_KEY_PREFIX;

@Slf4j
@Component
public class DataSyncTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    private ClueMapper clueMapper;
    
    @Autowired
    private BusinessMapper businessMapper;

    /**
     * 定时同步门户概览数据到Redis
     * 每30分钟执行一次
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void syncPortalOverviewToRedis() {
        try {
            log.info("开始执行门户概览数据同步到Redis任务");
            
            // 查询数据库数据
            ClueCountDO clueCountDO = clueMapper.selectCountClue();
            BusinessCountDO businessCountDO = businessMapper.selectCountBusiness();
            
            // 构造返回对象
            PortalVO vo = new PortalVO();
            if (clueCountDO != null) {
                // 复制clueCountDO属性到vo
                BeanUtil.copyProperties(clueCountDO, vo);
                // 根据实际BeanUtil.copyProperties逻辑实现
                vo.setClueTotal(clueCountDO.getClueTotal());
            }
            if (businessCountDO != null && vo != null) {
                // 复制businessCountDO属性到vo
                BeanUtil.copyProperties(businessCountDO, vo);
                // 根据实际BeanUtil.copyProperties逻辑实现
                vo.setBusinessTotal(businessCountDO.getBusinessTotal());
            }
            
            // 构造缓存key，与RedisAspect中保持一致
            String key = CACHE_PORTAL_KEY_PREFIX + "getOverview";
            
            // 存入Redis，设置24小时过期时间，与@Cacheable注解保持一致
            if (vo != null) {
                stringRedisTemplate.opsForValue().set(
                    key, 
                    JSONUtil.toJsonStr(vo), 
                    24 * 60, 
                    TimeUnit.MINUTES
                );
                log.info("门户概览数据同步完成，缓存key: {}", key);
            }
            
        } catch (Exception e) {
            log.error("门户概览数据同步失败", e);
        }
    }
}
